# -*- coding: utf-8 -*-

#    Copyright (C) 2005-2014 by Promotux
#                        di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of Promogest.

#    Promogest is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    Promogest is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with Promogest.  If not, see <http://www.gnu.org/licenses/>.

import datetime
from web_lib.page import Page
from web_lib.webutils import Response, expose, json, salvaInSessione, leggiInSessione, permalinkaTitle
import Environment
from web_lib.session import Session as S
from lib.utils import prep2json
from webEnv import *


@expose('/pg/ac_Faq/<action>')
@expose('/pg/ac_Faq/')
@expose('/pg/ac_Faq')
def anagraficaFaq(req, action=None):
    """
        Column('id', Integer, primary_key=True),
        Column('question', String(200), nullable=False),
        Column('argomento', String(200), nullable=True),
        Column('tags', String(600), nullable=True),
        Column('answer', Text, nullable=True),
        Column('imagepath', String(400), nullable=True),
        Column('insert_date', DateTime, nullable=True),
        Column('clicks', Integer),
        Column("permalink", String(500), nullable=True),
        Column('active', Boolean, default=0),
    """
    from dao.Setconf import SetConf
    def __show__(req, action=None):
        pageData = {'file': "/pg/ac_Faq"}
        return Page(req).render(pageData)

    def __list__(req, action=None):
        from dao.Faq import Faq
        sorting = req.args.get("jtSorting")
        offset = req.args.get("jtStartIndex")
        batchSize = req.args.get("jtPageSize")
        fk_denominazione = req.form.get("fk_denominazione")
        daos = Faq().select(
                            #denominazione=fk_denominazione,
                            batchSize=batchSize,
                            offset=offset,
                            orderBy=sorting)
        count = Faq().count(
                                    #denominazione=fk_denominazione,
                                    batchSize=None)
        #print daos[0].jsanity()

        item = {
            "Result":"OK",
            "TotalRecordCount": count,
            "Records": prep2json(daos)
            }
        #print "QUI", prep2json(daos)
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __edit__(req, action=None):
        from dao.Faq import Faq
        id = req.form.get("id")
        if id:
            d = Faq().getRecord(id=int(id))
        else:
            d = Faq()

        pageData = {'file': "pg/addedit/ae_faq",
                    "dao": d,
                    }
        return Page(req).render(pageData)

    def __create__update__(req, action=None):
        """Aggiunge una riga alle pesate"""
        from dao.Faq import Faq
        idrr = S(req).getUserId()
        id = req.form.get("id")
        if id != "None":
            d = Faq().getRecord(id=int(id))
        else:
            d = Faq()
            d.insert_date = datetime.datetime.utcnow()
        d.question = str(req.form.get("question"))
        d.argomento = str(req.form.get("argomento"))
        d.tags = str(req.form.get("tags"))
        d.answer = str(req.form.get("answer"))
        d.active = bool(req.form.get("active"))
        d.permalink = permalinkaTitle(req.form.get('question'))
        d.persist()
        url_red = "/pg/ac_Faq/"
        return Page(req).redirect(url_red)

    def __delete__(req, action=None):
        """Cancella una riga"""
        from dao.Faq import Faq
        id = int(req.form.get("id"))
        d = Faq().getRecord(id=id)
        try:
            d.delete()
            item = {"Result": "OK", }
        except:
            item = {
                "Result":"ERROR",
                "Message": "Cancellazione riga non riuscita"}
        jasoned = json.dumps(item)
        return Response(jasoned)

    def __preview__(req, action=None):
        from dao.Faq import Faq
        id = req.form.get("id")
        #salvaInSessione(req, chiave="id_fornitore_selezionato", valore=id)
        d = Faq().getRecord(id=id)
        pageData = {'file': "/pg/faq_detail",
                    "faq": d}
        return Page(req).render(pageData)


    if action=="List":
        return __list__ (req, action=action)
    elif action=="show":
        return __show__(req, action=action)
    elif action=="Create" or action == "Update":
        return __create__update__(req, action=action)
    elif action=="Delete":
        return __delete__(req, action=action)
    elif action == "GetMagazzino":
        return __get_mag__(req, action=action)
    elif action == "Edit":
        return __edit__(req, action=action)
    elif action == "Preview":
        return __preview__(req, action=action)
    else:
        return __show__(req, action=action)
